import Vue from 'vue'
import VueRouter from 'vue-router'
import jwDecode from 'jwt-decode'

Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    name: 'login',
    component: () => import('../views/Login.vue')
  },


  {
    path: '/index',
    name: 'index',
    component: () => import('../views/Index.vue'),
    children: [
      {
        path: '/welcome',
        name: 'welcome',
        component: () => import('../views/Welcome.vue'),
      },
      {
        path: '/users',
        name: 'users',
        component: () => import('../views/Users.vue'),
      },
      {
        path: '/roles',
        name: 'roles',
        component: () => import('../views/Roles.vue'),
      },
      {
        path: '/rights',
        name: 'rights',
        component: () => import('../views/Rights.vue'),
      },
      {
        path: '/goods',
        name: 'goods',
        component: () => import('../views/Goods.vue'),

      },
      {
        path: '/params',
        name: 'params',
        component: () => import('../views/Params.vue'),
      },
      {
        path: '/orders',
        name: 'orders',
        component: () => import('../views/Orders.vue'),
      },
      {
        path: '/categories',
        name: 'categories',
        component: () => import('../views/Categories.vue'),
      },
      {
        path: "/reports",
        name: 'reports',
        component: () => import('../views/Reports.vue'),
      },
      {
        path: '/add',
        name: 'add',
        component: () => import('../views/Add.vue'),
      }

    ]

  }
]

const router = new VueRouter({
  routes
})
//路由守卫
router.beforeEach((to, from, next) => {
  if (to.path == "/") {
    return next();

  }
  let token = localStorage.getItem('token')
  if (token) {
    let result = jwDecode(token)
    let nowtime = parseInt(new Date().getTime() / 1000)
    if (nowtime - result.exp > 0) {
      next("/")
    } else {
      next()
    }
  }else {
    next("/")
  }


})

export default router
